"""图片相似度计算
TODO
"""

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image


class Similarity(object):
    @staticmethod
    def histogram_similarity(
        im1: Image.Image, im2: Image.Image, draw: bool = False
    ) -> float:
        """计算两张图片的灰度直方图相似度

        Args:
            im1, im2: 输入图片
            draw: 是否画出图片的灰度直方图，默认不画出
        """
        COLOR_DEPTH = 256

        im1_array = np.asarray(im1.convert("L"), dtype=np.uint8)
        im2_array = np.asarray(im2.convert("L"), dtype=np.uint8)
        hist1, bin_edge1 = np.histogram(im1_array, bins=COLOR_DEPTH, density=True)
        hist2, bin_edge2 = np.histogram(im2_array, bins=COLOR_DEPTH, density=True)

        # TODO：直方图相似度计算，巴氏距离

        if draw:
            fig, ax = plt.subplots()
            ax.plot(hist1)
            ax.plot(hist2)
            ax.legend(['im1', 'im2'])

            plt.show()

        pass

    pass


if __name__ == '__main__':
    import os

    with Image.open(os.path.expanduser('~/Downloads/吔屎啦你.jpeg')) as im1:
        with Image.open(os.path.expanduser('~/Downloads/旺达与巨像.jpg')) as im2:
            Similarity.histogram_similarity(im1, im2, draw=True)
    pass